package com.mrdeer.common.util;

import com.google.gson.Gson;
import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.Region;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import com.qiniu.util.IOUtils;
import lombok.extern.slf4j.Slf4j;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.UUID;

/**
 * 七牛云的测试工具类
 *
 * @author: xie jianchu
 * @create_date: 2020/8/13 0013
 */
@Slf4j
public class QiniuUtil {
    /**
     * 文件上传的工具方法
     *
     * @param accessKey
     * @param secretKey
     * @param bucket
     * @param bytes
     * @param fileName  外部要传进来,七牛云上的文件名称和此保持一致
     */
    public static void update2Qiniu(String accessKey, String secretKey, String bucket, byte[] bytes, String fileName) {
        //构造一个带指定 Region 对象的配置类
        Configuration cfg = new Configuration(Region.huanan());
        //...其他参数参考类注释

        UploadManager uploadManager = new UploadManager(cfg);
        //...生成上传凭证，然后准备上传
//        String accessKey = "U7GdXfnU75WHFV7P1-ZqdFEQLI0p7GYvJhz3hAIj";
//        String secretKey = "IucWVpz8uKWDhLx0MUkrVfRPL38xw8suXbxPvMa3";
//        String bucket = "xpay-mrdeer";

        //默认不指定key的情况下，以文件内容的hash值作为文件名
        String key = fileName;
//        FileInputStream fileInputStream = null;
        //            String filePath = "C:\\Users\\20004883\\Pictures\\mmexport1593313069568.jpg";
//            fileInputStream = new FileInputStream(new File(fileName));
        //得到本地文件的字节数组
//            byte[] bytes = IOUtils.toByteArray(fileInputStream);
//            byte[] uploadBytes = "hello qiniu cloud".getBytes("utf-8");
        //认证
        Auth auth = Auth.create(accessKey, secretKey);
        //认证通过之后得到一个token
        String upToken = auth.uploadToken(bucket);

        try {
            //上传文件，参数:字节数组，key，token令牌
            //key:建议生成一个不重复的名称
//                key = UUID.randomUUID().toString() + "-" + System.currentTimeMillis() + ".jpg";
            Response response = uploadManager.put(bytes, key, upToken);
            //解析上传成功的结果
            DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
            System.out.println(putRet.key);
            System.out.println(putRet.hash);
        } catch (QiniuException ex) {
            Response r = ex.response;
            System.err.println(r.toString());
            log.error("上传文件到七牛云出错:{}", r.toString());
            try {
                System.err.println(r.bodyString());
                log.error(r.bodyString());
            } catch (QiniuException ex2) {
                //ignore
                throw new RuntimeException(ex2.getMessage());
            }
        }
    }

    /**
     * 测试文件上传
     */
    private static void testUpload() {
        //构造一个带指定 Region 对象的配置类
        Configuration cfg = new Configuration(Region.huanan());
        //...其他参数参考类注释

        UploadManager uploadManager = new UploadManager(cfg);
        //...生成上传凭证，然后准备上传
        String accessKey = "U7GdXfnU75WHFV7P1-ZqdFEQLI0p7GYvJhz3hAIj";
        String secretKey = "IucWVpz8uKWDhLx0MUkrVfRPL38xw8suXbxPvMa3";
        String bucket = "xpay-mrdeer";

        //默认不指定key的情况下，以文件内容的hash值作为文件名
        String key = null;
        FileInputStream fileInputStream = null;
        try {
            String filePath = "C:\\Users\\20004883\\Pictures\\mmexport1593313069568.jpg";
            fileInputStream = new FileInputStream(new File(filePath));
            //得到本地文件的字节数组
            byte[] bytes = IOUtils.toByteArray(fileInputStream);
//            byte[] uploadBytes = "hello qiniu cloud".getBytes("utf-8");
            //认证
            Auth auth = Auth.create(accessKey, secretKey);
            //认证通过之后得到一个token
            String upToken = auth.uploadToken(bucket);

            try {
                //上传文件，参数:字节数组，key，token令牌
                //key:建议生成一个不重复的名称
                key = UUID.randomUUID().toString() + "-" + System.currentTimeMillis() + ".jpg";
                Response response = uploadManager.put(bytes, key, upToken);
                //解析上传成功的结果
                DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
                System.out.println(putRet.key);
                System.out.println(putRet.hash);
            } catch (QiniuException ex) {
                Response r = ex.response;
                System.err.println(r.toString());
                try {
                    System.err.println(r.bodyString());
                } catch (QiniuException ex2) {
                    //ignore
                }
                throw new RuntimeException(r.bodyString());
            }
        } catch (IOException ex) {
            //ignore
            throw new RuntimeException(ex.getMessage());
        }
    }

    private static void getDownloadUrl() throws UnsupportedEncodingException {
        String fileName = "683479ee-ce96-41bb-9d30-fd5c0439e041-1597298786134.jpg";
        String domainOfBucket = "xpay-mrdeer.s3-cn-south-1.qiniucs.com";
        String encodedFileName = URLEncoder.encode(fileName, "utf-8").replace("+", "%20");
        String publicUrl = String.format("%s/%s", domainOfBucket, encodedFileName);

        String accessKey = "U7GdXfnU75WHFV7P1-ZqdFEQLI0p7GYvJhz3hAIj";
        String secretKey = "IucWVpz8uKWDhLx0MUkrVfRPL38xw8suXbxPvMa3";
        Auth auth = Auth.create(accessKey, secretKey);
        long expireInSeconds = 3600;//1小时，可以自定义链接过期时间
        String finalUrl = auth.privateDownloadUrl(publicUrl, expireInSeconds);

        System.out.println(finalUrl);

    }

    public static void main(String[] args) throws UnsupportedEncodingException {
        //上传测试
//        QiniuUtil.testUpload();
        QiniuUtil.getDownloadUrl();
    }
}
